//
//  WYRChatViewController.m
//  10-21-快速搭建框架
//
//  Created by lkx0 on 16/10/27.
//  Copyright © 2016年 lkx0. All rights reserved.
//

#import "WYRChatViewController.h"
#import "WYRNavigationController.h"
#import "WYRTwoViewController.h"
#import "WYRMessage.h"
#import "WYRMessageCell.h"
#import "WYRMeaasgeframe.h"

@interface WYRChatViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
//使用一个可变数组来保存所有的消息模型对象
@property(nonatomic, strong) NSMutableArray * messageFrames;
@property(nonatomic, strong) UITableView * tbView;
@property(nonatomic,strong)UIView *inputView;

//输入栏的uiview
//1.语音键
@property(nonatomic,strong)UIButton *soundBtn;
//2.输入框
@property(nonatomic,strong)UITextField *inputFd;
//3.表情键
@property(nonatomic,strong)UIButton *faceBtn;
//4.加号键
@property(nonatomic,strong)UIButton *plusBtn;

@end

@implementation WYRChatViewController
//重写messages的set方法（懒加载）
-(NSMutableArray *)messageFrames{
    //如果已经有了这份数据，那就不在加载新的，只有该数据不存在的时候才加载
    if(_messageFrames== nil){
        //加载模型数据
        //1.将plist文件中的数据保存到一个新的字典数组中
        NSString * path=[[NSBundle mainBundle]pathForResource:@"messages.plist" ofType:nil];
        //1.2 将plist文件中的所有字典保存到一个数组中
        NSArray * arrayDict=[NSArray arrayWithContentsOfFile:path];
        //2.创建一个可变数组来接收所有的模型对象
        NSMutableArray * arrayModels=[NSMutableArray array];
        //3.转化字典模型
        for (NSDictionary * dict in arrayDict) {
            //3.1创建一个消息模型
            WYRMessage * model=[WYRMessage messageWithDict:dict];
            
            WYRMeaasgeframe *modelFrame=[[WYRMeaasgeframe alloc]init];
            
            modelFrame.message=model;
            
            //3.2将模型对象添加到数组
            [arrayModels addObject:modelFrame];
        }
        //4.将保存所有模型对象的数组赋给属性变量
        _messageFrames=arrayModels;
        
}
    return _messageFrames;
}


- (void)viewDidLoad {
    [super viewDidLoad];
   // self.view.backgroundColor=[UIColor colorWithRed:200/255 green:200/255 blue:200/255 alpha:1.0];
    self.view.backgroundColor=[UIColor whiteColor];
    [self messageFrames];
    [self setNav];
   
    
    //设置tableView
    CGSize screenSize=[UIScreen mainScreen].bounds.size;
    CGRect tbFrame=CGRectMake(0,0,screenSize.width, screenSize.height-50);
    
    
    _tbView=[[UITableView alloc]initWithFrame:tbFrame style:UITableViewStylePlain];
    _tbView.dataSource=self;
    _tbView.delegate=self;
    
    //设置tableView背景色
    _tbView.backgroundColor=[UIColor grayColor];
    //取消分割线
    _tbView.separatorStyle=NO;
    
    [self.view addSubview:_tbView];
    
    //添加聊天输入栏
    [self addInput];
    
    //处理键盘的弹出事件，避免键盘弹出覆盖消息输入栏
    
    //1. 发布者：系统
    //2.监听者：self
    //3.通知中心：center
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    
    [center addObserver:self selector:@selector(keyboardUp:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    //设置
    self.inputFd.delegate=self;
    
}

//实现通知的方法、
-(void)keyboardUp:(NSNotification *)notoInfo{
   // NSLog(@"键盘弹起来了注意！");
    //1.获取键盘最大值
    CGRect rectEnd=[notoInfo.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat keyboardY=rectEnd.origin.y;
    
    //2.计算聊天界面要往上平移的高度
    CGFloat upValue=keyboardY-self.view.bounds.size.height;
    
    //3.实现键盘弹出时平移动画的效果
    [UIView animateWithDuration:0.25 animations:^{self.view.transform=CGAffineTransformMakeTranslation(0, upValue);}];
    
}

-(void)addInput{
        //初始化inputView
    _inputView=[[UIView alloc]initWithFrame:CGRectMake(0, _tbView.bounds.size.height, _tbView.bounds.size.width, 60)];
    _inputView.backgroundColor=[UIColor whiteColor];
    
    //输入栏的uiview
    //1.语音键
    _soundBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
   // _soundBtn.backgroundColor=[UIColor redColor];
    
    //设置语音按钮背景图
    [self setVBtnBackImage:_soundBtn andImgName:@"chat_bottom_voice_nor" andImgName2:@"chat_bottom_voice_press"];
       [_inputView addSubview:_soundBtn];
    
    //2.输入框
    _inputFd=[[UITextField alloc]initWithFrame:CGRectMake(60, 10, _tbView.bounds.size.width-180, 60)];
    [_inputFd setBackground:[UIImage imageNamed:@"chat_bottom_textfield"]];
    //_inputFd.backgroundColor=[UIColor purpleColor];
    
    //在左边添加一个空白View 让光标左移动
    UIView *leftVw=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 40)];
    _inputFd.leftView=leftVw;
    
    _inputFd.leftViewMode=UITextFieldViewModeAlways;
    
    [_inputView addSubview:_inputFd];
    
    //3.表情键
    _faceBtn=[[UIButton alloc]initWithFrame:CGRectMake(_tbView.bounds.size.width-120, 0, 60, 60)];
    [_faceBtn setBackgroundImage:[UIImage imageNamed:@"chat_bottom_smile_nor"] forState:UIControlStateNormal];
    [_faceBtn setBackgroundImage:[UIImage imageNamed:@"chat_bottom_smile_press"] forState:UIControlStateHighlighted];
    //_faceBtn.backgroundColor=[UIColor yellowColor];
    [_inputView addSubview:_faceBtn];
    

    //4.加号键
    _plusBtn=[[UIButton alloc]initWithFrame:CGRectMake(_tbView.bounds.size.width-60, 0, 60, 60)];
    [self setVBtnBackImage:_faceBtn andImgName:@"chat_bottom_up_nor" andImgName2:@"chat_bottom_up_press"];
    
    
    
    //_plusBtn.backgroundColor=[UIColor redColor];
    [_inputView addSubview:_plusBtn];
    
    
    
    
    
    [self.view addSubview:_inputView];



}


//封装设置按钮背景图方法
-(void)setVBtnBackImage:(UIButton *)btn andImgName:(NSString *)imgName andImgName2:(NSString *)imgName2{
    
    
    //设置按钮背景图
    [btn setBackgroundImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:imgName2] forState:UIControlStateHighlighted];

}


#pragma mark - 文本输入框代理方法

//获取文本框内容（文本输入框的代理）
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
//发送按钮被点击，输入框代理方法
    //1.获取文本框内容
    NSString *text=textField.text;
    
    //2.发送该内容
    [self sendMessage:WYRMessageTypeMe withText:text];
    
    //3.模拟别人回复消息
    [self sendMessage:WYRMessageTypeOher withText:@"我现在很忙，待会儿回复你"] ;
    
    //4.清空输入框
    textField.text=nil;
    
    
    return YES;

}

//发送消息的分装方法
-(void)sendMessage:(WYRMessageType)type withText:(NSString *)text{
    //1.创建数据模型对象
    WYRMessage *model=[[WYRMessage alloc]init];
    
    //设置数据模型的数据
    //1.1正文
    model.text=text;
    //1.2发送时间  ，当前时间
    NSDate *nowDate=[NSDate date];
    
    //转成：（今天HH：MM）
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    formatter.dateFormat=@"今天 HH:mm";
    model.time=[formatter stringFromDate:nowDate];
    
    //1.3类别
    model.type=type;

    //2.创建frame模型对象
    WYRMeaasgeframe *modelFrame=[[WYRMeaasgeframe alloc]init];
    
    //3.将数据模型对象添加到frame模型
    modelFrame.message=model;
    
    //4.将新的的frame模型对象添加到frame模型数组中
    [_messageFrames addObject:modelFrame];
    //5.刷新tableView
    [_tbView reloadData];
    //66.将最新的消息显示在最后一行
    
    //获取发送消息后的tableview的indexpath
    NSIndexPath *lastIndexPath=[NSIndexPath indexPathForRow:_messageFrames.count-1 inSection:0];
    
    //将最后一行平移上来
    [_tbView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}



#pragma mark - 数据源方法
//当tableView滚动的时候回收键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];

}




#pragma mark - 数据源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _messageFrames.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //获取模型
    WYRMeaasgeframe *modelFrame=self.messageFrames
    [indexPath.row];
    //创建cell
    static NSString *ID=@"message_cell";
    WYRMessageCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    //判断cell是否为空 为空说明程序没有cell
    if (cell==nil) {
        cell=[[WYRMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
    }
    //把frame模型设置给cell
    cell.messageFrame=modelFrame;
    return cell;
    
}


//返回行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    WYRMeaasgeframe *messageFrame=self.messageFrames[indexPath.row];
    
    return messageFrame.rowHeight;
    
    
}




#pragma mark - 其他方法
 //导航栏数据设置
-(void)setNav{
    UIBarButtonItem * barItem=[[UIBarButtonItem alloc]initWithTitle:@"消息(12)" style:UIBarButtonItemStylePlain target:self action:@selector(message)];
    self.navigationItem.leftBarButtonItem=barItem;
    

}


-(void)message{
    WYRTwoViewController * two=[[WYRTwoViewController alloc]init];
    [self.navigationController pushViewController:two animated:YES];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self popoverPresentationController];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
